import React, { useState } from 'react';
import { Radio, DatePicker, Space } from 'antd';
import { TimeRange } from '../../../types/hotRadar';
import dayjs, { Dayjs } from 'dayjs';
import './style.css';

const { RangePicker } = DatePicker;

interface TimeFilterProps {
  value?: TimeRange | { start: string; end: string };
  onChange?: (value: TimeRange | { start: string; end: string }) => void;
}

export const TimeFilter: React.FC<TimeFilterProps> = ({
  value = TimeRange.LATEST,
  onChange,
}) => {
  const [customRange, setCustomRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [radioValue, setRadioValue] = useState(
    typeof value === 'string' ? value : TimeRange.CUSTOM
  );

  const handleRadioChange = (e: any) => {
    const newValue = e.target.value;
    setRadioValue(newValue);
    
    if (newValue !== TimeRange.CUSTOM) {
      onChange?.(newValue);
      setCustomRange(null);
    }
  };

  const handleRangeChange = (dates: any) => {
    if (dates && dates[0] && dates[1]) {
      setCustomRange(dates);
      setRadioValue(TimeRange.CUSTOM);
      onChange?.({
        start: dates[0].startOf('day').toISOString(),
        end: dates[1].endOf('day').toISOString(),
      });
    }
  };

  const timeOptions = [
    { label: '最新', value: TimeRange.LATEST },
    { label: '今天', value: TimeRange.TODAY },
    { label: '24小时', value: TimeRange.DAY },
    { label: '7天', value: TimeRange.WEEK },
    { label: '自定义', value: TimeRange.CUSTOM },
  ];

  return (
    <div className="time-filter">
      <label className="filter-label">时间范围：</label>
      <Space direction="vertical" style={{ flex: 1 }}>
        <Radio.Group
          value={radioValue}
          onChange={handleRadioChange}
          optionType="button"
          buttonStyle="solid"
          options={timeOptions}
        />
        
        {radioValue === TimeRange.CUSTOM && (
          <RangePicker
            value={customRange}
            onChange={handleRangeChange}
            style={{ width: '100%' }}
            placeholder={['开始日期', '结束日期']}
            disabledDate={(current) => {
              return current && current > dayjs().endOf('day');
            }}
          />
        )}
      </Space>
    </div>
  );
};